package com.linghang.wusthelper.redis.impl;

import com.linghang.wusthelper.redis.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author origin
 * redis工具类
 */
@Service("RedisService")
public class RedisServiceImpl implements RedisService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 普通缓存存入
     * @param key
     * @param value
     * @return
     */
    @Override
    public boolean set(String key, String value) {
        try {
            stringRedisTemplate.opsForValue().set(key,value);
            return true;
        }catch (Exception ex){
            log.error("存入缓存失败:"+key+ex);
            return false;
        }
    }

    /**
     * 获取普通缓存
     * @param key
     * @return
     */
    @Override
    public String get(String key) {
        try {
            return stringRedisTemplate.opsForValue().get(key);
        }catch (Exception ex){
            log.error("获取缓存失败："+key);
            return null;
        }

    }

    /**
     * 删除缓存
     * @param key
     * @return
     */
    @Override
    public boolean remove(String key) {
        try{
            stringRedisTemplate.delete(key);
            return true;
        }catch (Exception ex){
            log.error("删除缓存失败："+key);
            return false;
        }
    }

    /**
     * 判断是否存在key
     * @param key
     * @return
     */
    @Override
    public boolean hasKey(String key) {
        return stringRedisTemplate.hasKey(key);
    }

    /**
     * 设置缓存过期时间
     * @param key
     * @param time
     * @return
     */
    @Override
    public boolean expire(String key, long time) {
        try{
            if (time > 0){
                stringRedisTemplate.expire(key,time, TimeUnit.SECONDS);
            }
            return true;
        }catch (Exception ex){
            log.error("设置过期时间失败："+key);
            return false;
        }
    }

    /**
     * 获取缓存过期时间
     * @param key
     * @return
     */
    @Override
    public long getExpire(String key) {
        return stringRedisTemplate.getExpire(key);
    }

    /**
     * 存入普通缓存及过期时间
     * @param key
     * @param value
     * @param time
     * @return
     */
    @Override
    public boolean set(String key, String value, long time) {
        try{
            stringRedisTemplate.opsForValue().set(key,value,time,TimeUnit.SECONDS);
            return true;
        }catch (Exception ex){
            ex.printStackTrace();
            log.error("设置缓存失败："+key);
            return false;
        }
    }
}
